package examples;

import cn.bmwm.navigate.DirectionUtil;
import com.sun.org.apache.xpath.internal.XPathAPI;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class NavigateUI extends javax.swing.JFrame {
    private DefaultListModel resultListModel = new DefaultListModel();
    private String status;
    private String type;
    private String distance ="0";
    private String duration="0";
    private String taxiDesc;
    private String taxiKmPrice;
    private String taxiStartPrice;
    private String taxiTotalPrice;
    private String taxiRemark;
    
    /**
     * Creates new form ContactEditor
     */
    public NavigateUI() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        parametersPanel = new javax.swing.JPanel();
        originRegionLabel = new javax.swing.JLabel();
        destinationRegionLabel = new javax.swing.JLabel();
        originRegionTextField = new javax.swing.JTextField();
        destinationRegionTextField = new javax.swing.JTextField();
        originLabel = new javax.swing.JLabel();
        originTextField = new javax.swing.JTextField();
        destinationLabel = new javax.swing.JLabel();
        destinationTextField = new javax.swing.JTextField();
        navigateInfoPanel = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        routesList = new javax.swing.JList();
        routeMsgLabel = new javax.swing.JLabel();
        taxiLabel = new javax.swing.JLabel();
        taxiRemarkLabel = new javax.swing.JLabel();
        clearButton = new javax.swing.JButton();
        navigateButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("线路规划导航器");

        parametersPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("导航参数"));

        originRegionLabel.setText("起点所在城市:");

        destinationRegionLabel.setText("目的地所在城市:");

        originRegionTextField.setText("上海");

        destinationRegionTextField.setText("上海");
        destinationRegionTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                destinationRegionTextFieldActionPerformed(evt);
            }
        });

        originLabel.setText("起点:");

        originTextField.setText("复旦大学");
        originTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                originTextFieldActionPerformed(evt);
            }
        });

        destinationLabel.setText("目的地:");

        destinationTextField.setText("金茂大厦");

        org.jdesktop.layout.GroupLayout parametersPanelLayout = new org.jdesktop.layout.GroupLayout(parametersPanel);
        parametersPanel.setLayout(parametersPanelLayout);
        parametersPanelLayout.setHorizontalGroup(
            parametersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(parametersPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(parametersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(destinationLabel)
                    .add(originLabel)
                    .add(originRegionLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(parametersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(parametersPanelLayout.createSequentialGroup()
                        .add(originRegionTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(destinationRegionLabel)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(destinationRegionTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE))
                    .add(originTextField)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, destinationTextField))
                .addContainerGap())
        );
        parametersPanelLayout.setVerticalGroup(
            parametersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(parametersPanelLayout.createSequentialGroup()
                .add(parametersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(originRegionLabel)
                    .add(destinationRegionTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(originRegionTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(destinationRegionLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(parametersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(originLabel)
                    .add(originTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(parametersPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(destinationLabel)
                    .add(destinationTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        navigateInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("导航信息"));
        navigateInfoPanel.setForeground(new java.awt.Color(0, 0, 204));
        navigateInfoPanel.setFont(new java.awt.Font("宋体", 0, 14)); // NOI18N

        jLabel6.setText("导航路径");
        jLabel6.setToolTipText("");

        jScrollPane1.setViewportView(routesList);

        routeMsgLabel.setFont(new java.awt.Font("微软雅黑", 0, 14)); // NOI18N
        routeMsgLabel.setForeground(new java.awt.Color(0, 0, 153));
        routeMsgLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        taxiLabel.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        taxiLabel.setForeground(new java.awt.Color(0, 0, 204));

        taxiRemarkLabel.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        taxiRemarkLabel.setForeground(new java.awt.Color(0, 0, 204));
        taxiRemarkLabel.setText("jLabel2");

        org.jdesktop.layout.GroupLayout navigateInfoPanelLayout = new org.jdesktop.layout.GroupLayout(navigateInfoPanel);
        navigateInfoPanel.setLayout(navigateInfoPanelLayout);
        navigateInfoPanelLayout.setHorizontalGroup(
            navigateInfoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, navigateInfoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(navigateInfoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(taxiRemarkLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, taxiLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, navigateInfoPanelLayout.createSequentialGroup()
                        .add(jLabel6)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(routeMsgLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        navigateInfoPanelLayout.setVerticalGroup(
            navigateInfoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(navigateInfoPanelLayout.createSequentialGroup()
                .add(navigateInfoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel6)
                    .add(routeMsgLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 178, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(taxiLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(taxiRemarkLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE))
        );

        clearButton.setText("清空");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        navigateButton.setText("导航");
        navigateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                navigateButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("微软雅黑", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 0, 51));

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(31, 31, 31)
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(navigateButton)
                        .add(18, 18, 18)
                        .add(clearButton))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(parametersPanel, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, navigateInfoPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );

        layout.linkSize(new java.awt.Component[] {clearButton, navigateButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(parametersPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(clearButton)
                    .add(navigateButton)
                    .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(navigateInfoPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        parametersPanel.getAccessibleContext().setAccessibleName("Name");
        navigateInfoPanel.getAccessibleContext().setAccessibleName(" E");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_clearButtonActionPerformed

    private void destinationRegionTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_destinationRegionTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_destinationRegionTextFieldActionPerformed

    private void originTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_originTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_originTextFieldActionPerformed

    private void navigateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_navigateButtonActionPerformed
      
        String  originRegion =   originRegionTextField.getText();
        String destinationRegion =   destinationRegionTextField.getText();
        String origin = originTextField.getText();
        String destination = destinationTextField.getText();
        System.out.println("起点所在城市 origin_region: " + originRegion);
        System.out.println("目标所在城市 destination_region: " + destinationRegion);
        System.out.println("起点 origin:" + origin);
        System.out.println("目的地 destination: " + destination);
        
         Document dom = DirectionUtil.navigate(origin, destination, originRegion, destinationRegion);

        try {
            status = XPathAPI.selectSingleNode(dom, "//status/text()").getNodeValue();
            
            if ("0".equals(status)) {//成功
                jLabel1.setText("导航成功!");
                type = XPathAPI.selectSingleNode(dom, "//type/text()").getNodeValue();
                if ("1".equals(type)) {
                    jLabel1.setText("起终点过于模糊，无法正确匹配，请重新输入!");
                } else {
                    distance = XPathAPI.selectSingleNode(dom, "//routes/distance/text()").getNodeValue();
                    duration = XPathAPI.selectSingleNode(dom, "//routes/duration/text()").getNodeValue();
                    String msg = "";
                    String taxiMsg = "";
                    if (distance != null) {
                        float km = Integer.parseInt(distance) / 1000.0f;
                        msg = msg + "全程约" + km + "公里;";
                    }
                    if (duration != null) {
                        int minutes = Integer.parseInt(duration) / 60;
                        msg = msg + "耗时约" + minutes + "分钟;";
                    }
                    routeMsgLabel.setText(msg);
                    
                    NodeList list = XPathAPI.selectNodeList(dom, "//steps/content/instructions/text()");
                    for (int i = 0; i < list.getLength(); ++i) {
                        resultListModel.addElement("<html>" + list.item(i).getNodeValue() + "</html>");
                    }
                    routesList.setModel(resultListModel);
                    
                    taxiDesc = XPathAPI.selectSingleNode(dom, "//taxi/detail/desc[1]/text()").getNodeValue();
                    taxiKmPrice = XPathAPI.selectSingleNode(dom, "//taxi/detail/km_price[1]/text()").getNodeValue();
                    taxiStartPrice= XPathAPI.selectSingleNode(dom, "//taxi/detail/start_price[1]/text()").getNodeValue();
                    taxiTotalPrice = XPathAPI.selectSingleNode(dom, "//taxi/detail/total_price[1]/text()").getNodeValue();
                    taxiRemark = XPathAPI.selectSingleNode(dom, "//taxi/remark/text()").getNodeValue();
                    if (taxiDesc != null) {
                        taxiMsg = taxiMsg +"打的信息:"+ taxiDesc+";";
                    }
                    if (taxiKmPrice != null) {
                        taxiMsg =taxiMsg + "每公里价格 "  + taxiKmPrice + "元;";
                    }
                    if (taxiStartPrice != null) {
                        taxiMsg = taxiMsg + "起步价 " + taxiStartPrice + "元;";
                    }
                    if (taxiTotalPrice != null) {
                        taxiMsg = taxiMsg + "总价约 " + taxiTotalPrice + "元;";
                    }
                    if (taxiRemark != null) {
                        taxiRemarkLabel.setText(taxiRemark);
                    }
                    taxiLabel.setText(taxiMsg);
                 
                }
            } else if ("2".equals(status)) {//参数错误
                jLabel1.setText("参数错误，请重新输入上面的表单!");
            } else if ("5".equals(status)) {//权限或配额校验失败
                jLabel1.setText("接口错误，权限或配额校验失败!");
            } else {
                jLabel1.setText("发生未知错误!");
            }
       
        } catch (TransformerException e) {
            e.printStackTrace();
        //    Log.warning("Translator error", e);
        }
     
       // System.out.println("导航路径 The result is:\n" + result);
        destinationTextField.requestFocusInWindow();       
    }//GEN-LAST:event_navigateButtonActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.LookAndFeelInfo[] installedLookAndFeels=javax.swing.UIManager.getInstalledLookAndFeels();
            for (int idx=0; idx<installedLookAndFeels.length; idx++)
                if ("Nimbus".equals(installedLookAndFeels[idx].getName())) {
                    javax.swing.UIManager.setLookAndFeel(installedLookAndFeels[idx].getClassName());
                    break;
                }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NavigateUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NavigateUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NavigateUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NavigateUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NavigateUI().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearButton;
    private javax.swing.JLabel destinationLabel;
    private javax.swing.JLabel destinationRegionLabel;
    private javax.swing.JTextField destinationRegionTextField;
    private javax.swing.JTextField destinationTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton navigateButton;
    private javax.swing.JPanel navigateInfoPanel;
    private javax.swing.JLabel originLabel;
    private javax.swing.JLabel originRegionLabel;
    private javax.swing.JTextField originRegionTextField;
    private javax.swing.JTextField originTextField;
    private javax.swing.JPanel parametersPanel;
    private javax.swing.JLabel routeMsgLabel;
    private javax.swing.JList routesList;
    private javax.swing.JLabel taxiLabel;
    private javax.swing.JLabel taxiRemarkLabel;
    // End of variables declaration//GEN-END:variables
    
}
